package com.ruoyi.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.framework.websocket.WebSocketJoinDomain;
import com.ruoyi.framework.websocket.WebSocketUsers;
import org.springframework.web.bind.annotation.*;
import javax.websocket.Session;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/hotel/webSocket")
public class WebSocketController {

    /**
     * 获取webSocket用户集
     *
     * @return
     */
    @GetMapping("/getWebSocketUsers")
    public List<String> getWebSocketUsers() {
        List<String> websocketUser = new ArrayList<>();
        Map<String, WebSocketJoinDomain> users = WebSocketUsers.getUsers();
        Set<Map.Entry<String, WebSocketJoinDomain>> entries = users.entrySet();
        for (Map.Entry<String, WebSocketJoinDomain> entry : entries) {
            String uid = entry.getValue().getUid();
            websocketUser.add(uid);
        }
        return websocketUser;
    }

    /**
     * 群发消息
     */
    @PostMapping("/sendMsg")
    public void sendMsg(@RequestBody JSONObject jsonObject) {
        WebSocketUsers.sendMessageToUsersByText(JSONObject.toJSONString(jsonObject));
    }

    /**
     * 关闭所有连接
     */
    @PostMapping("/closeAllConnections")
    public void closeAllConnections() {
        Map<String, WebSocketJoinDomain> users = WebSocketUsers.getUsers();
        Set<Map.Entry<String, WebSocketJoinDomain>> entries = users.entrySet();
        for (Map.Entry<String, WebSocketJoinDomain> entry : entries) {
            Session session = entry.getValue().getSession();
            if (session.isOpen()) {
                try {
                    session.close();
                } catch (IOException e) {
                    // 处理关闭失败的情况
                    e.printStackTrace();
                }
            }
        }
        users.clear();
    }
}
